package serialtool;

import com.engidea.comm.CommPort;
import com.engidea.comm.CommPortIdentifier;
import com.engidea.comm.SerialPort;
import com.engidea.comm.SerialPortEvent;
import com.engidea.comm.SerialPortEventListener;
import com.engidea.win32jcom.WinjcomIdentifier;
import drinkkiosk.Settings;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * Simple class that can list system ports and allow IO
 */
public class SerialTool {
	private String port = Settings.getSerialPort();
    private String results = "";
    /**
     * 
     * @param input
     * @return
     */
    public String getResult(String input) {
        return this.StartTest(input);
    }
    private CommPortIdentifier portIdentifier;
    private SerialPort serport;
    /**
     * 
     */
    public static String buffer;

    private void report(String msg) {
        System.out.println(msg);
    }

    private String StartTest(String input) {
        portIdentifier = new WinjcomIdentifier(0);
        //listComPorts();
        selectComport();
        PortReader portReader = new PortReader();
        new Thread(portReader).start();
        getResults(input);
        try {
            //typeSendBytes();
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(SerialTool.class.getName()).log(Level.SEVERE, null, ex);
        }
        serport.close();
        return portReader.getResults();
    }

    private void typeSendBytes() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String aStr = "";
            while (aStr != null) {
                //System.out.print("type something to send> ");
                aStr = in.readLine();
                aStr += "\r\n";
                // WARNING: be careful, you shoulod select the encoding !
                // This will timeout if you have FLOW CONTROL and theline is stuck !
                byte[] buf = aStr.getBytes();
                serport.write(buf, 0, buf.length);
            }
        } catch (Exception exc) {
        }
    }

    private void getResults(String input) {
        try {
            //BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String aStr = "";
            //while (aStr != null) 
            //{
            //System.out.print("type something to send> ");
            aStr = input;//in.readLine();
            aStr += "\r\n";
            // WARNING: be careful, you shoulod select the encoding !
            // This will timeout if you have FLOW CONTROL and theline is stuck !
            byte[] buf = aStr.getBytes();
            serport.write(buf, 0, buf.length);

            //}
        } catch (Exception exc) {
        }
    }

    private void listComPorts() {
        List portlist = portIdentifier.getCommPortList();
        for (Iterator iter = portlist.iterator(); iter.hasNext();) {
            CommPort identifier = (CommPort) iter.next();
            System.out.println("Available port name=" + identifier.getName());
        }
    }

    private SerialPort openPort(String portName) {
        try {
            CommPort aPort = portIdentifier.getCommPort(port);
            aPort.open();
            return (SerialPort) aPort;
        } catch (Exception exc) {
            report("exc=" + exc);
        }

        return null;
    }

    private void selectComport() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

            //System.out.print("type port name> ");
            //String portname = in.readLine();
            //String portname = "COM4";
            //System.out.println("portname:"+portname);
            serport = openPort("");
            serport.setSerialPortParams(9600, 8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
            serport.enableReceiveTimeout(100);
            serport.setEventListener(new EventListener());

            serport.notifyOnDSR(true);
            serport.notifyOnCarrierDetect(true);
            serport.notifyOnCTS(true);
//      serport.notifyOnOutputEmpty(true);
        } catch (IOException exc) {
            report("Exc=" + exc);
        }
    }

    private final class EventListener implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent ev) {
            System.out.println("Got event=" + ev);
        }
    }

    private final class PortReader implements Runnable {

        private String results = "";

        public synchronized String getResults() {
            return this.results;
        }

        @Override
        public void run() {
            try {
                // This will timeout if nothing is received in the specified time.
                byte[] buff = new byte[1];
                while (serport.read(buff, 0, buff.length) > 0) {
                    // NOTE: you should be checking the encoding !
//		System.out.print(new String(buff));
                    if (Character.isDigit(new String(buff).toCharArray()[0])) {
                        this.results += new String(buff);
                    }
                    buffer = new String(buff);
                }
            } catch (Exception exc) {
            }
        }
    }
}
